// 解析json为字段
import {
  checkboxConfig,
  dateConfig,
  inputConfig,
  numberConfig,
  radioConfig,
  selectConfig
} from "@/views/formgen/components/GenerateForm/config";
import { toLower } from "lodash-es";

/**
 * 测试数据
 * [
 *     {
 *         "type": "单行文本",
 *         "title": "您的姓名？"
 *     },
 *     {
 *         "type": "日期",
 *         "title": "您用餐的日期？"
 *     },
 *     {
 *         "type": "数字",
 *         "title": "您用餐的人数？"
 *     },
 *     {
 *         "type": "单选",
 *         "title": "您对食堂的总体满意度如何？",
 *         "options": [
 *             "非常满意",
 *             "满意",
 *             "一般",
 *             "不满意",
 *             "非常不满意"
 *         ]
 *     },
 *     {
 *         "type": "多选",
 *         "title": "您对食堂的哪些方面感到满意？",
 *         "options": [
 *             "菜品种类",
 *             "菜品味道",
 *             "服务态度",
 *             "环境卫生",
 *             "价格合理"
 *         ]
 *     },
 *     {
 *         "type": "下拉",
 *         "title": "您最喜欢的菜品是什么？",
 *         "options": [
 *             "红烧肉",
 *             "宫保鸡丁",
 *             "水煮鱼",
 *             "酸菜鱼",
 *             "西红柿炒鸡蛋"
 *         ]
 *     }
 * ]
 * @param json
 */
const filedTypeMap: any = {
  单行文本: inputConfig,
  日期: dateConfig,
  数字: numberConfig,
  单选: radioConfig,
  多选: checkboxConfig,
  下拉: selectConfig
};

export const parseJsonToFields = (json: string) => {
  const jsonArr = JSON.parse(json);
  // 转换成表单数据
  const fields = jsonArr.map((item: any, index: number) => {
    const field = filedTypeMap[item.type];
    if (field) {
      field.config.label = item.title;
    }
    if (field.config.options) {
      field.config.options = item.options.map((op: string, index: string) => {
        return {
          label: op,
          value: index
        };
      });
    }
    // 找到题目数据定义
    field.config.formId = `${toLower(field.typeId)}${new Date().getTime() + index}`;
    field.vModel = field.config.formId;
    return field;
  });
  return fields;
};
